<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use think\Facade\Config as Configs;
use app\models\{User as Users, SignLog, UserConfig, UserAuth, UserSafety, Moneylog, Levelup, Team, Machine, MachineLog, SmsLog};

class User extends Base
{
    public function index()
    {
        $model = new Users();
        $data = $this->request->get();
        if (!empty($data['order']) && $data['order'] == 1) {
            $list = $model->order('money desc');
        } elseif (!empty($data['order']) && $data['order'] == 2) {
            $list = $model->order('amount desc');
        } elseif (!empty($data['order']) && $data['order'] == 3) {
            $list = $model->order('quota desc');
        } elseif (!empty($data['order']) && $data['order'] == 4) {
            $list = $model->order('power desc');
        } else {
            $list = $model->order('id desc');
        }
        if (!empty($data['level'])) {
            $list = $list->where('level', $data['level']);
        }
        if (!empty($data['mobile'])) {
            $list = $list->where('id|mobile', $data['mobile']);
        }
        if (!empty($data['pmobile'])) {
            $pid = (new Users())->where('id|mobile', $data['pmobile'])->value('id');
            $list = $list->where('pid', $pid);
        }
        if (!empty($data['ppmobile'])) {
            $ppid = (new Users())->where('id|mobile', $data['ppmobile'])->value('id');
            $list = $list->where('pid', $ppid);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()])->each(function ($item) {
            if ($item['pid'] > 0) {
                $item['pmobile'] = (new Users())->where('id', $item['pid'])->value('mobile');
            }
            if ($item['ppid'] > 0) {
                $item['ppmobile'] = (new Users())->where('id', $item['ppid'])->value('mobile');
            }
            $userauth = (new UserAuth())->where(['user_id' => $item['id'], 'status' => 2])->find();
            $item['userauth'] = !empty($userauth) ? 2 : 1;
            return $item;
        });
        return view('', ['list' => $list]);
    }

    public function moneylog()
    {
        $model = new Moneylog();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['cointype'])) {
            $list = $list->where('cointype', $data['cointype']);
        }
        if (!empty($data['mobile'])) {
            $user_id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $user_id);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()])->each(function ($item) {
            $item['mobile'] = (new Users())->where('id', $item['user_id'])->value('mobile');
            if ($item['comeuser_id'] > 0) {
                $item['comeuser_mobile'] = (new Users())->where('id', $item['comeuser_id'])->value('mobile');
            }
            $item['moneytext'] = Configs::get('config.cointype')[$item['cointype']];
            if ($item['cointype'] == 1) {
                $item['typetext'] = Configs::get('config.money')[$item['type']];
            }
            if ($item['cointype'] == 2) {
                $item['typetext'] = Configs::get('config.amount')[$item['type']];
            }
            if ($item['cointype'] == 3) {
                $item['typetext'] = Configs::get('config.quota')[$item['type']];
            }
            if ($item['cointype'] == 4) {
                $item['typetext'] = Configs::get('config.assets')[$item['type']];
            }
            if ($item['cointype'] == 4) {
                $item['typetext'] = Configs::get('config.power')[$item['type']];
            }
            return $item;
        });
        return view('', ['list' => $list, 'coin' => Configs::get('config.cointype')]);
    }

    public function smslog()
    {
        $model = new SmsLog();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $list = $list->where('mobile', $data['mobile']);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function moneystr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'type' => 'require|in:1,2,3,4,5,10',
                'money' => 'require|float',
            ], [
                'id.require' => '用户ID不能为空',
                'id.gt' => '用户必须大于0',
                'type.require' => '资产类型不能为空',
                'type.in' => '资产类型不正确',
                'money.require' => '修改数目不能为空',
                'money.float' => '修改数目必须是数字或小数',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where(['id' => $data['id']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
            }
            if ($data['money'] == 0 || ($data['money'] < 0 && abs($data['money']) > $user['money'])) {
                return json(['status' => 1, 'data' => [], 'msg' => '修改数目不能为0或修改后资产数目为负数']);
            }
            Db::startTrans();
            try {
                if ($data['type'] == 1) {
                    (new Users())->MoneyEdit($user['id'], $user['money'], $data['money'], $data['type'], 3, '新增资产');
                }
                if ($data['type'] == 2) {
                    (new Users())->MoneyEdit($user['id'], $user['amount'], $data['money'], $data['type'], 5, '新增资产');
                }
                if ($data['type'] == 3) {
                    (new Users())->MoneyEdit($user['id'], $user['quota'], $data['money'], $data['type'], 3, '新增资产');
                }
                if ($data['type'] == 4) {
                    (new Users())->MoneyEdit($user['id'], $user['assets'], $data['money'], $data['type'], 1, '新增资产');
                }
                if ($data['type'] == 5) {
                    (new Users())->MoneyEdit($user['id'], $user['power'], $data['money'], $data['type'], 3, '新增资产');
                }
                if ($data['type'] == 10) {
                    (new Users())->where('id', $user['id'])->setInc('reputa', $data['money']);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            return view();
        }
    }


    public function statusstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'status' => 'require|in:0,1',
            ], [
                'id.require' => '用户ID不能为空',
                'id.gt' => '用户必须大于0',
                'status.require' => '类型不能为空',
                'status.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where(['id' => $data['id']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
            }
            Db::startTrans();
            try {
                (new Users())->where('id', $user['id'])->update(['status' => $data['status']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            return view();
        }
    }


    public function giveminging()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'machineid' =>  'require|gt:0'
            ], [
                'id.require' => '用户ID不能为空',
                'id.gt' => '用户必须大于0',
                'machineid.require' => '矿机ID不能为空',
                'machineid.gt' => '矿机必须大于0',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $machine = (new Machine())->where(['id' => $data['machineid'], 'status' => 1])->find();
            if (empty($machine)) {
                return json(['status' => 1, 'data' => [], 'msg' => '矿机不存在或已下架']);
            }
            $user = (new Users())->where('id', $data['id'])->find();
            Db::startTrans();
            try {
                $id = (new MachineLog())->insertGetId([
                    'user_id' => $data['id'],
                    'buymoney' => $machine['price'],
                    'power' => $machine['power'],
                    'mining_id' => $machine['id'],
                    'dividends' => $machine['dividends'],
                    'day_dividends' => $machine['day_dividends'],
                    'day' => $machine['day'],
                    'lave_day' => $machine['day'],
                    'type' => 1,
                    'text' => '后台添加',
                    'days' => date('Y-m-d H:i:s')
                ]);
                if ($machine['power'] > 0) {
                    (new Users())->MoneyEdit($user['id'], $user['power'], $machine['power'], 5, 2, '购买矿机[系统]', $id, 0, 0, 0);
                }
                Redis::lPush('lists', $user['id']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '购买失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '购买成功']);
        } else {
            $id = $this->request->get('id/d', 0);
            $machine = (new Machine())->select();
            return view('', ['machine' => $machine, 'id' => $id]);
        }
    }

    public function userauth()
    {
        $model = new UserAuth();
        $data = $this->request->get();
        $list = $model->order('user_id desc');
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['card_no'])) {
            $list = $list->where('name|card_no', 'like', '%' . $data['card_no'] . '%');
        }
        if (!empty($data['mobile'])) {
            $user_id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $user_id);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()])->each(function ($item) {
            $item['mobile'] = (new Users())->where('id', $item['user_id'])->value('mobile');
            return $item;
        });
        return view('', ['list' => $list]);
    }


    public function userauthstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'status' => 'require|in:2,3'
            ], [
                'id.require' => '用户ID不能为空',
                'id.gt' => '用户必须大于0',
                'status.require' => '资产类型不能为空',
                'status.in' => '资产类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = (new UserAuth())->where(['user_id' => $data['id']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
            }

            Db::startTrans();
            try {
                (new UserAuth())->where(['user_id' => $data['id']])->update(['status' => $data['status']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '审核失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '审核成功']);
        } else {
            return view();
        }
    }


    public function userconfig()
    {
        $model = new UserConfig();
        $data = $this->request->get();
        $list = $model->order('level desc');
        $list = $list->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function userconfigstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $model = new UserConfig();
            $data = $this->request->post();
            $validate = new Validate([
                'level' => 'require|gt:0'
            ], [
                'level.require' => 'ID不能为空',
                'level.gt' => 'ID必须大于0'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = $model->where(['level' => $data['level']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
            }
            Db::startTrans();
            try {
                $model->allowfield(true)->save($data, ['level' => $data['level']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '编辑失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '编辑成功']);
        } else {
            $id = $this->request->get('level/d', 0);
            $list = (new UserConfig())->where('level', $id)->find();
            return view('', ['row' => $list]);
        }
    }

    public function user_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $model = new Users();
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
                'level' => 'require',
                'mobile' => 'require'
            ], [
                'id.require' => '用户ID不能为空',
                'id.gt' => '用户必须大于0',
                'level.require' => '用户等级不能为空',
                'mobile.require' => '手机账号不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = $model->where(['id' => $data['id']])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
            }
            if ($user['mobile'] != $data['mobile']) {
                $haveuser = $model->where(['mobile' => $data['mobile']])->find();
                if (!empty($haveuser)) {
                    return json(['status' => 1, 'data' => [], 'msg' => '手机账号已存在']);
                }
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            } else {
                unset($data['password']);
            }
            if (!empty($data['trade'])) {
                $data['trade'] = md5(md5($data['trade']));
            } else {
                unset($data['trade']);
            }
            Db::startTrans();
            try {
                $model->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($user['level'] != $data['level']) {
                    (new Levelup())->insert([
                        'user_id' => $data['id'],
                        'type' => 2,
                        'levelbf' => $user['level'],
                        'levelaf' => $data['level']
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '修改失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            $id = $this->request->get('id/d', 0);
            $list = (new Users())->where('id', $id)->find();
            $userconfig = (new UserConfig())->select();
            return view('', ['row' => $list, 'userconfig' => $userconfig]);
        }
    }


    public function user_add()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $model = new Users();
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require|chsAlphaNum',
                'mobile' => 'require',
                'invit' => 'require|gt:0',
                'password' => 'require',
                'trade' => 'require',
            ], [
                'nickname.require' => '昵称不能为空',
                'chsAlphaNum.require' => '昵称必须是汉字、字母或数字',
                'mobile.require' => '手机号不能为空',
                'invit.require' => '邀请码不能为空',
                'invit.gt' => '邀请码错误',
                'password.require' => '登录密码不能为空',
                'trade.require' => '支付密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[0-9]{10}$/", $data['mobile'])) {
                return json(['status' => 1, 'data' => [], 'msg' => '手机号格式不正确']);
            }
            //判断邀请码是否存在
            $code = (new Users())->where('code', $data['invit'])->find();
            if (empty($code)) {
                return json(['status' => 1, 'data' => [], 'msg' => '邀请码错误']);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where('mobile', $data['mobile'])->find();
            if (!empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '手机号码已注册']);
            }
            if (empty($code['structure'])) {
                $structure = $code['id'];
            } else {
                $structure = $code['structure'] . ',' . $code['id'];
            }
            $people = explode(',', $structure);
            $people = array_filter($people); //给上级人员增加团队人数
            $people = array_reverse($people);
            $mycode = recode(new Users());
            $teamdata = [];
            Db::startTrans();
            try {
                $id = (new Users())->insertGetId([
                    'mobile' => $data['mobile'],
                    'nickname' => $data['nickname'],
                    'password' => md5(md5($data['password'])),
                    'trade' => md5(md5($data['trade'])),
                    'code' => $mycode,
                    'pid' => $code['id'],
                    'ppid' => $code['pid'],
                    'structure' => $structure,
                    'created' => date('Y-m-d H:i:s')
                ]);
                foreach ($people as $k => $v) {
                    $teamdata[] = ['user_id' => $v, 'supe_id' => $id, 'algebra' => ($k + 1), 'dates' => date('Y-m-d')];
                }
                if (!empty($teamdata)) {
                    (new Team())->insertAll($teamdata);
                }
                Redis::lPush('lists', $id);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '注册失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '注册成功']);
        } else {
            return view('', []);
        }
    }

    public function signlog()
    {
        $model = new SignLog();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $user_id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $user_id);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()])->each(function ($item) {
            $item['mobile'] = (new Users())->where('id', $item['user_id'])->value('mobile');
            return $item;
        });
        return view('', ['list' => $list]);
    }

    public function userauthfast()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $model = new Users();
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'name' => 'require',
                'card_no' => 'require',
            ], [
                'id.require' => '用户ID不能为空',
                'name.require' => '姓名不能为空',
                'card_no.require' => '身份证号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //判断手机号码是否已存在
            $user = (new Users())->where('id', $data['id'])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
            }
            //判断是否实名
            $userauth = (new UserAuth())->where('user_id', $data['id'])->find();
            if (!empty($userauth) && $userauth['status'] == 2) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户已实名']);
            }
            Db::startTrans();
            try {
                if (!empty($userauth)) {
                    (new UserAuth())->where('user_id', $data['id'])->update(['status' => 2, 'info' => '后台快速实名', 'name' => $data['name'], 'card_no' => $data['card_no']]);
                } else {
                    (new UserAuth())->insert(['user_id' => $data['id'], 'status' => 2, 'info' => '后台快速实名', 'name' => $data['name'], 'card_no' => $data['card_no']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => '实名失败，请重试']);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '实名成功']);
        }
    }


    public function usersafety()
    {
        $model = new UserSafety();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $user_id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $user_id);
        }
        $list = $list->paginate(10, false, ['query' => $this->request->param()])->each(function ($item) {
            $item['mobile'] = (new Users())->where('id', $item['user_id'])->value('mobile');
            return $item;
        });
        return view('', ['list' => $list]);
    }

    //用户层级关系
    public function userteam()
    {
        return view();
    }

    public function userteamstr()
    {
        $data = $this->request->get();
        if (isset($data['mobile']) && !isset($data['id'])) {
            $data['id'] = (new Users())->where('id|mobile',  $data['mobile'])->value('id');
        }
        if (!isset($data['id'])) {
            $data['id'] = 0;
        }
        $results = (new Users())->where('pid',  $data['id'])->select();
        $arr = [];
        foreach ($results as $k => $result) {
            $arr[$k]['count'] = count($results);
            $arr[$k]['id'] = $result['id'];
            $arr[$k]['name'] = $result['mobile'];
            $arr[$k]['isParent'] = 'true';
        }
        return json($arr);
    }

    public function usersafetystr()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $model = new UserSafety();
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'type' => 'require|in:1,2,3',
        ], [
            'id.require' => '用户ID不能为空',
            'type.require' => '类型不能为空',
            'type.in' => '类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $safety = $model->where(['user_id' => $data['id'], 'type' => $data['type']])->find();
        if (empty($safety)) {
            return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
        }
        $res = $model->where(['user_id' => $data['id'], 'type' => $data['type']])->delete();
        if ($res) {
            return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['status' => 1, 'data' => [], 'msg' => '操作失败']);
    }
}
